package com.syh.jn.scm.main;

import cn.redscarf.commons.util.other.ClassUtils;
import cn.redscarf.commons.spring.SpringContextUtils;
import com.syh.core.ddd.domain.DomainEvent;
import com.syh.core.ddd.event.annotation.DomainEventHandle;
import com.syh.core.eventBus.EventHandle;
import com.syh.jn.scm.infrastructure.eventBus.reflex.ReflexEventBus;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

public class InitEventBus {


	public static void initReflexEventBus() {
		ReflexEventBus reflexEventBus = ReflexEventBus.getEventBus();

		List<Method> methodList = ClassUtils.getMethodByAnnotation("com.syh.jn.scm.service.impl", DomainEventHandle.class);
		for (Method method : methodList) {
			DomainEventHandle entity = method.getAnnotation(DomainEventHandle.class);
			String[] handleEventNames = entity.value();
			Arrays.stream(handleEventNames).forEach(handleEventName -> {
				reflexEventBus.subscribe(handleEventName, new EventHandle() {
					@Override
					public void handle(DomainEvent domainEvent) throws InvocationTargetException, IllegalAccessException {
						Class<?> clazz = method.getDeclaringClass();
						String name = clazz.getSimpleName();
						name = name.substring(0, 1).toLowerCase().concat(name.substring(1, name.length()));
						Object[] params = domainEvent.getValues() != null ? domainEvent.getValues() : null;
						method.invoke(SpringContextUtils.getBean(name), params);
					}
				});
			});

		}
	}

}
